import router from '@/router/index'
import store from '@/store/index'
import asyncRoutes from '@/router/asyncRoutes'
const whiteList = ['/login','/404']
//获取一级权限标识
function getFirstRouterPermission(permission){
 const firstPermission =  permission.map(item=>{
   return item.split(':')[0]
  })
  // return Array.from(new Set(firstPermission))
  return [...new Set(firstPermission)]
}
//获取二级权限标识
function getSecondRouterPermission(permission){
  const secondPermission =  permission.map((item,index)=>{
    const arr =  item.split(':')
    return `${arr[0]}:${arr[1]}`
   })
   return [...new Set(secondPermission)]
 }
 //刷选动态路由
 function getRoutes(firstPermission,secondPermission,asyncRoutes){
  //筛选一级动态路由
  //判读一级路由是不是*，如果是就是管理员不需要筛选
  if(firstPermission.includes('*')){
    return asyncRoutes
  }
  const firstRoutes =  asyncRoutes.filter(item=>{
    return firstPermission.includes(item.permission)
  })
  //筛选二级动态路由
  // return firstRoutes.children.filter(item=>{
  //   return secondPermission.includes(item.permission)
  // })
  const routes = firstRoutes.map(item=>{
    return {
      ...item,
      children:item.children.filter(child=>secondPermission.includes(child.permission))
    }
  })
  return routes
 }
//全局前置守卫
router.beforeEach(async(to,from,next)=>{
  //to 跳转的路由 from 从哪里来 next 放行next() 重定向next(重定向)
  const  token = store.state.user.token
  if(token){
    if(to.path==='/login'){
      next('/')
    }else{
      next()
      //1.拿到用户权限信息
     const permission = await store.dispatch('menu/getUserPermission')
     console.log(permission,'permission')
      //2.根据权限标识刷选出一级路由
      const firstPermission =  getFirstRouterPermission(permission)
      //3.根据权限标识刷选出二级路由
      const secondPermission = getSecondRouterPermission(permission)
      //4.根据一二级数据刷选动态路由
      const routes = getRoutes(firstPermission,secondPermission,asyncRoutes)
      console.log(routes,'routes....')
      //5.把筛选的路由 导入到左侧
      routes.forEach(item=>{
        router.addRoute(item)
      })
      //6.把动态路由存进vuex
      store.commit('menu/setMenuList',routes)
    }
  }else{
    if(whiteList.includes(to.path)){
      next()
    }else{
      next('/login')
      // next('/login?redirect='+to.path)
    }
  } 
})